package com.sk.weichat.ui.account;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.sk.weichat.MyApplication;
import com.sk.weichat.R;
import com.sk.weichat.adapter.MessageLogin;
import com.sk.weichat.bean.Code;
import com.sk.weichat.bean.LoginRegisterResult;
import com.sk.weichat.bean.SMSCheckCodeBean;
import com.sk.weichat.db.dao.UserDao;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.helper.LoginHelper;
import com.sk.weichat.helper.PrivacySettingHelper;
import com.sk.weichat.ui.MainActivity;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.DestroyActivityUtil;
import com.sk.weichat.util.DeviceInfoUtil;
import com.sk.weichat.util.EventBusHelper;
import com.sk.weichat.util.PreferenceUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.VerificationCodeView;
import com.sk.weichat.volley.Result;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import okhttp3.Call;

/**
 * 验证码填写Activity
 */
public class SMSCodeActivity extends BaseActivity {

    private String phoneNum = "";
    private String areaCode = "";
    private String isLogin = "";
    private String isResetPsw = "";

    private Button btnSend;

    private VerificationCodeView verificationcodeview;

    private int mOldLoginStatus;

    private SMSReceiver smsReceiver;

    private TextView tvTips;
    private String openId;
    private String type;
    private String loginType;

    public SMSCodeActivity() {
        noLoginRequired();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//暗色主题状态栏(白字)
            this.getWindow().getDecorView()
                    .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_VISIBLE);
        }
        setContentView(R.layout.activity_sms_code);
        getSupportActionBar().hide();
        findViewById(R.id.mergerStatus).setBackgroundColor(Color.parseColor("#00000000"));

        phoneNum = getIntent().getStringExtra("phoneNum");
        areaCode = getIntent().getStringExtra("areaCode");
        isLogin = getIntent().getStringExtra("isLogin");
        isResetPsw = getIntent().getStringExtra("isResetPsw");
        openId = getIntent().getStringExtra("openId");
        type = getIntent().getStringExtra("type");
        loginType = getIntent().getStringExtra("loginType");
        verificationcodeview = findViewById(R.id.verificationcodeview);
        btnSend = findViewById(R.id.btn_send_sms_again);
        tvTips = findViewById(R.id.tv_send_code_tips);
        mOldLoginStatus = MyApplication.getInstance().mUserStatus;
        smsReceiver = new SMSReceiver();
        initEvent();
        countDownTimer.start();
        tvTips.setText("已发送验证码至 +" + areaCode + " " + phoneNum);
    }

    //初始化控件相关事件或逻辑
    private void initEvent() {
        verificationcodeview.setOnCodeFinishListener(new VerificationCodeView.OnCodeFinishListener() {
            @Override
            public void onComplete(String content) {
                if (!TextUtils.isEmpty(isLogin)) {
                    if (isLogin.equals("1")) {//登录
                        loginByCode();
                    } else if (isLogin.equals("0")) {//修改密码
                        checkSetPswCode();
                    } else if (isLogin.equals("2")) {//修改手机号
                        updatePhoneCode();
                    }
                }
            }
        });
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestAuthCode();
            }
        });
        ImageView ivBack = findViewById(R.id.iv_title_left);
        ivBack.setImageResource(R.mipmap.ic_back_white);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
//        requestAuthCode();
        EventBusHelper.register(this);
    }

    CountDownTimer countDownTimer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            btnSend.setEnabled(false);
            btnSend.setTextColor(mContext.getResources().getColor(R.color.white));
            btnSend.setBackgroundResource(R.drawable.bg_round_white_35);
            btnSend.setText(mContext.getString(R.string.send_again) + " (" + (millisUntilFinished / 1000) + ")");
        }

        @Override
        public void onFinish() {
            btnSend.setTextColor(mContext.getResources().getColor(R.color.deep_purple));
            btnSend.setBackgroundResource(R.drawable.bg_round_white);
            btnSend.setEnabled(true);
            btnSend.setText(mContext.getString(R.string.send_again));
        }
    };

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(MessageLogin message) {
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //注册获取短信的广播接收器
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
        registerReceiver(smsReceiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //解开注册广播接收器
        unregisterReceiver(smsReceiver);
    }

    /**
     * 请求验证码
     */
    private void requestAuthCode() {
        Map<String, String> params = new HashMap<>();
        String language = Locale.getDefault().getLanguage();
        params.put("language", language);
        params.put("areaCode", areaCode);
        params.put("telephone", phoneNum.replace(" ", ""));
        params.put("openId", TextUtils.isEmpty(openId) ? "" : openId);
        params.put("type", TextUtils.isEmpty(type) ? "" : type);
        DialogHelper.showMessageProgressDialog(this, "正在请求验证码...");
        HttpUtils.get().url(coreManager.getConfig().SEND_LOGIN_CODE)
                .params(params)
                .build()
                .execute(new BaseCallback<Code>(Code.class) {

                    @Override
                    public void onResponse(ObjectResult<Code> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            countDownTimer.start();
//                            ToastUtil.showToast(mContext, getString(R.string.verification_code_send_success));
                            tvTips.setText("已发送验证码至 +" + areaCode + " " + phoneNum);
                        } else {
                            String message = TextUtils.isEmpty(result.getResultMsg()) ? "验证码获取失败" : result.getResultMsg();
                            ToastUtil.showToast(mContext, message);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showNetError(mContext);
                    }
                });
    }

    /**
     * 使用验证码登录
     */
    private void loginByCode() {
        Map<String, String> params = new HashMap<>();
        String language = Locale.getDefault().getLanguage();
        String verificationCode = verificationcodeview.getAllNum();
        params.put("language", language);
        params.put("areaCode", areaCode);
        params.put("type", TextUtils.isEmpty(loginType) ? "" : loginType);
        params.put("openId", TextUtils.isEmpty(openId) ? "" : openId);
        params.put("telephone", phoneNum.replace(" ", ""));
        params.put("verificationCode", verificationCode);
        params.put("apiVersion", DeviceInfoUtil.getVersionCode(mContext) + "");
        params.put("model", DeviceInfoUtil.getModel());
        params.put("osVersion", DeviceInfoUtil.getOsVersion());
        params.put("serial", DeviceInfoUtil.getDeviceId(mContext));
        params.put("latitude", String.valueOf(MyApplication.getInstance().getBdLocationHelper().getLatitude()));
        params.put("longitude", String.valueOf(MyApplication.getInstance().getBdLocationHelper().getLongitude()));
        DialogHelper.showMessageProgressDialog(this, "正在登录...");
        HttpUtils.get().url(coreManager.getConfig().LOGIN_BY_CODE)
                .params(params)
                .build()
                .execute(new BaseCallback<LoginRegisterResult>(LoginRegisterResult.class) {

                    @Override
                    public void onResponse(ObjectResult<LoginRegisterResult> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result == null) {
                            DialogHelper.dismissProgressDialog();
                            ToastUtil.showErrorData(mContext);
                            verificationcodeview.clearAllNum();
                            return;
                        }
                        if (result.getData() == null || result.getResultCode() != 1) {
                            String message = TextUtils.isEmpty(result.getResultMsg()) ? getString(R.string.login_failed) : result.getResultMsg();
                            ToastUtil.showToast(mContext, message);
                            tvTips.setText(message);
                            verificationcodeview.clearAllNum();
                            return;
                        }
                        //如果上个界面是BandAndChangePhoneActivity则关闭
                        DestroyActivityUtil.destoryActivity("BandAndChangePhoneActivity");
                        if (result.getData().getIsRegister() == 1) {
                            boolean success = false;
                            if (result.getResultCode() == Result.CODE_SUCCESS) {
                                success = LoginHelper.setLoginUser(mContext, coreManager, phoneNum, result.getData().getPassword(), result);// 设置登录用户信息
                            }
                            if (success) {
                                PreferenceUtils.putBoolean(SMSCodeActivity.this, Constants.LOGIN_CONFLICT, false);// 重置登录冲突记录
                                LoginRegisterResult.Settings settings = result.getData().getSettings();
                                MyApplication.getInstance().initPayPassword(result.getData().getUserId(), result.getData().getPayPassword());
                                PrivacySettingHelper.setPrivacySettings(SMSCodeActivity.this, settings);
                                // 登录成功
                                LoginRegisterResult.Login login = result.getData().getLogin();
                                //判断是否是添加多账号
                                MultiAccountHelper.onLoginSuccess(mContext, result.getData().getUserId());
                                if (!TextUtils.isEmpty(type)) {//微信QQ第一次授权登录需要更新信息
                                    mOldLoginStatus = LoginHelper.STATUS_USER_NO_UPDATE;
                                }
                                if (login != null && login.getSerial() != null && login.getSerial().equals(DeviceInfoUtil.getDeviceId(mContext))
                                        && mOldLoginStatus != LoginHelper.STATUS_USER_NO_UPDATE && mOldLoginStatus != LoginHelper.STATUS_NO_USER) {
                                    // 如果Token没变，上次更新也是完整更新，那么直接进入Main程序
                                    // 其他的登录地方都需进入DataDownloadActivity，在DataDownloadActivity里发送此广播
                                    LoginHelper.broadcastLogin(SMSCodeActivity.this);
                                    Intent intent = new Intent(SMSCodeActivity.this, MainActivity.class);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivity(intent);
                                } else {
                                    // 否则，进入数据下载界面
                                    startActivity(new Intent(SMSCodeActivity.this, DataDownloadActivity.class));
                                }
                                finish();
                            } else {
                                // 登录失败
                                String message = TextUtils.isEmpty(result.getResultMsg()) ? getString(R.string.login_failed) : result.getResultMsg();
                                ToastUtil.showToast(mContext, message);
                                tvTips.setText(message);
                                verificationcodeview.clearAllNum();
                            }
                        } else {
//                            RegisterUserBasicInfoActivity.start(
//                                    SMSCodeActivity.this,
//                                    "" + areaCode,
//                                    phoneNum,
//                                    "",
//                                    verificationCode,
//                                    result.getData().getNickName(),
//                                    result.getData().getAccess_token()
//                            );

                            Intent intent = new Intent(getApplicationContext(), RegisterUserBasicInfoActivity.class);
                            intent.putExtra(RegisterActivity.EXTRA_AUTH_CODE, "" + areaCode);
                            intent.putExtra(RegisterActivity.EXTRA_PHONE_NUMBER, phoneNum);
                            intent.putExtra(RegisterActivity.EXTRA_INVITE_CODE, verificationCode);
                            intent.putExtra(RegisterActivity.EXTRA_PASSWORD, "");
                            String nickname = getIntent().getStringExtra("nickname");
                            intent.putExtra("nickname", TextUtils.isEmpty(nickname) ? result.getData().getNickName() : nickname);
                            intent.putExtra("sex", getIntent().getStringExtra("sex"));
                            intent.putExtra("imgurl", getIntent().getStringExtra("imgurl"));
                            intent.putExtra("thirdToken", "");
                            startActivity(intent);
                            finish();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showNetError(mContext);
                    }
                });
    }

    /**
     * 请求 校验修改密码的验证码 接口
     */
    private void checkSetPswCode() {
        Map<String, String> params = new HashMap<>();
        String verificationCode = verificationcodeview.getAllNum();
        String phoneStr = phoneNum.replace(" ", "");
        params.put("areaCode", areaCode);
        params.put("telephone", phoneStr);
        params.put("verificationCode", verificationCode);
        DialogHelper.showMessageProgressDialog(this, "正在校验验证码...");
        HttpUtils.get().url(coreManager.getConfig().CHECK_PSW_CODE)
                .params(params)
                .build()
                .execute(new BaseCallback<SMSCheckCodeBean>(SMSCheckCodeBean.class) {

                    @Override
                    public void onResponse(ObjectResult<SMSCheckCodeBean> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result == null) {
                            DialogHelper.dismissProgressDialog();
                            ToastUtil.showErrorData(mContext);
                            verificationcodeview.clearAllNum();
                            return;
                        }
                        if (result.getData() == null) {
                            String message = TextUtils.isEmpty(result.getResultMsg()) ? getString(R.string.login_failed) : result.getResultMsg();
                            ToastUtil.showToast(mContext, message);
                            tvTips.setText(message);
                            verificationcodeview.clearAllNum();
                            return;
                        }
                        if (result.getResultCode() == 1) {
                            if (!TextUtils.isEmpty(result.getData().getSk())) {//跳转至设置密码界面
                                String sk = result.getData().getSk();
                                Intent intent = new Intent(SMSCodeActivity.this, SetPasswordActivity.class);
                                intent.putExtra("telephone", phoneStr);
                                intent.putExtra("areaCode", areaCode);
                                intent.putExtra("sk", sk);
                                intent.putExtra("from", Integer.parseInt(isResetPsw));
                                startActivity(intent);
                                finish();
                            }
                        } else {
                            String message = TextUtils.isEmpty(result.getResultMsg()) ? getString(R.string.login_failed) : result.getResultMsg();
                            ToastUtil.showToast(mContext, message);
                            tvTips.setText(message);
                            verificationcodeview.clearAllNum();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showNetError(mContext);
                    }
                });
    }

    /**
     * 请求 修改手机号 接口
     */
    private void updatePhoneCode() {
        Map<String, String> params = new HashMap<>();
        String verificationCode = verificationcodeview.getAllNum();
        String phoneStr = phoneNum.replace(" ", "");
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("areaCode", areaCode);
        params.put("telephone", phoneStr);
        params.put("verificationCode", verificationCode);
        DialogHelper.showMessageProgressDialog(this, "正在校验验证码...");
        HttpUtils.get().url(coreManager.getConfig().UPDATE_PHONE)
                .params(params)
                .build()
                .execute(new BaseCallback<SMSCheckCodeBean>(SMSCheckCodeBean.class) {

                    @Override
                    public void onResponse(ObjectResult<SMSCheckCodeBean> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result == null) {
                            DialogHelper.dismissProgressDialog();
                            ToastUtil.showErrorData(mContext);
                            verificationcodeview.clearAllNum();
                            return;
                        }

                        if (result.getResultCode() == 1) {
                            ToastUtil.showToast(mContext, result.getResultMsg());
                            DestroyActivityUtil.destoryActivity("BandAndChangePhoneActivity");
                            coreManager.getSelf().setPhone(phoneStr);
                            UserDao.getInstance().updateTelephone(coreManager.getSelf().getUserId(), phoneStr);     // 更新数据库
                            finish();
                        } else {
                            String message = TextUtils.isEmpty(result.getResultMsg()) ? getString(R.string.login_failed) : result.getResultMsg();
                            ToastUtil.showToast(mContext, message);
                            tvTips.setText(message);
                            verificationcodeview.clearAllNum();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showNetError(mContext);
                    }
                });
    }

    //接收短信的系统广播
    public class SMSReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //进行获取短信的操作
            getMsg(intent);
        }

    }

    //获取短信内容
    private void getMsg(Intent intent) {
        //pdus短信单位pdu
        //解析短信内容
        Object[] pdus = (Object[]) intent.getExtras().get("pdus");
        assert pdus != null;
        for (Object pdu : pdus) {
            //封装短信参数的对象
            SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdu);
            String number = sms.getOriginatingAddress();
            String body = sms.getMessageBody();
            //写自己的处理逻辑
            //获取短信验证码
            getCode(body);
        }
    }

    //提取短信的验证码
    private void getCode(String body) {
        if (body.startsWith("【欢乐果】您的验证码")) {
            //获取剪贴板管理器：
            Pattern pattern = Pattern.compile("(\\d{4})");//提取四位数字
            Matcher matcher = pattern.matcher(body);//进行匹配
            if (matcher.find()) {//匹配成功
                String code = matcher.group(0);
                verificationcodeview.setAllNum(code);
            }
        }
    }

}
